package cn.wolfcode.shop.web.controller;

import cn.wolfcode.shop.anno.UserParam;
import cn.wolfcode.shop.common.BusinessException;
import cn.wolfcode.shop.common.Result;
import cn.wolfcode.shop.domain.User;
import cn.wolfcode.shop.msg.SeckillServerCodeMsg;
import cn.wolfcode.shop.service.ISeckillGoodService;
import cn.wolfcode.shop.util.RedisKeys;
import cn.wolfcode.shop.vo.SeckillGoodVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/path")
public class RandomPathController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ISeckillGoodService seckillGoodService;

    @RequestMapping
    public Result<String> getPath(@UserParam User user, Long seckillId, String verifyCode) {
        if (user == null || seckillId == null || StringUtils.isEmpty(verifyCode)) {
            throw new BusinessException(SeckillServerCodeMsg.OPS_ERROR);
        }
        // 验证码校验
        String ret = redisTemplate.opsForValue()
                .get(RedisKeys.SECKILL_VIREFY_CODE.join(user.getId() + "", seckillId + ""));
        if (StringUtils.isEmpty(ret) || !ret.equals(verifyCode)) {
            throw new BusinessException(SeckillServerCodeMsg.VERIFY_CODE_ERROR);
        }

        // 删除通过校验的验证码,将Redis中校验通过的验证码删除，因为验证过就失效了，没有必要占用空间
        redisTemplate.delete(RedisKeys.SECKILL_VIREFY_CODE.join(user.getId() + "", seckillId + ""));

        // 检查是否处于秒杀活动进行中，不在没有必要获取 random
        SeckillGoodVO seckillGoodVO = seckillGoodService.findByCache(seckillId);
        Date now = new Date();  // 当前时间
        //   当前小于开始时间，活动未开始
        if (now.compareTo(seckillGoodVO.getStartDate()) < 0) {
            throw new BusinessException(SeckillServerCodeMsg.NOT_START_ERROR);
        }
        //   当前大于等于结束时间，活动已结束
        if (now.compareTo(seckillGoodVO.getEndDate()) >= 0) {
            throw new BusinessException(SeckillServerCodeMsg.ALREADY_OVER_ERROR);
        }
        // 1. 生成uuid随机数
        String random = UUID.randomUUID().toString();
        // 2. 将uuid随机数保存进Redis中，设置有效时间，(key关联用户和秒杀场)
        redisTemplate.opsForValue().set(
                RedisKeys.RANDOM_IN_PATH.join(user.getId() + "", seckillId + ""),
                random,
                RedisKeys.RANDOM_IN_PATH.getTime(),
                TimeUnit.SECONDS);
        // 3. 返回uuid随机数
        return Result.success(random);
    }
}
